package gwtadmin.client;

import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class PanelSwitcher extends VerticalPanel {

	private Panel centralP;
	
	public PanelSwitcher(Panel root) {
		super();
		centralP = root;
		if (root == null)
			centralP = RootPanel.get("centralP");
	}
	
	public int addWidget(Widget panel) {
		
		if (count >= panels.length)
			return -1;
		
		panel.setVisible(false);
		centralP.add(panel);
		
		panels[count++] = panel;
		return count;
	}
	
	public void SwitchTo(Widget panel) {
		int index = getIndex(current);
		if (index != -1) {
			panels[index].setVisible(false);
		}
		index = getIndex(panel);
		if (index != -1) {
			panels[index].setVisible(true);
		}
		prev = current;
		current = panel;
	}
	
	public void goBack() {
		if (prev != null) {
			SwitchTo(prev);
			prev = null;
		}
	}
	
	private int getIndex(Widget vp) {
		for (int i = 0; i < count; i++) {
			if (vp == panels[i])
				return i;
		}
		return -1;
	}
	
	Widget current = null;
	Widget prev = null;
	
	int count = 0;
	Widget[] panels = { null, null, null, null, null, null, null, null };
}
